package com.esunrising.esungsc.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.esunrising.esungsc.common.utils.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

@RestController
@RequestMapping("/demo")
@Slf4j
public class DemoController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/index")
    public String index(){
        return "Hello, world!";
    }

    /**
     * 测试基本Get请求
     * @return
     */
    @GetMapping("/get1")
    public Object get1(){
        String url = "http://localhost:8889/esungsc/index/encode";
        Map<String, String> uriVariables = new HashMap<>();
        uriVariables.put("str", "yuzudeng");

        // 置入Query参数
        String uri = HttpUtil.putQueryParam(url, uriVariables);

        String forObject = restTemplate.getForObject(uri, String.class); // 返回一个String
        // Query参数也可以使用占位符形式
        // 如：
        // String url = "http://localhost:8889/esungsc/index/encode?str={str}";
        // String forObject = restTemplate.getForObject(uri, String.class, uriVariables);

        System.out.println(forObject);
        return forObject;
    }

    /**
     * 测试结果Json字符串解析
     * @return
     */
    @GetMapping("/get2")
    public Object get2(){
        String url = "http://localhost:8889/esungsc/index/json";
        Map<String, String> uriVariables = new HashMap<>();
        uriVariables.put("str", "yuzudeng");

        // 置入Query参数
        String uri = HttpUtil.putQueryParam(url, uriVariables);

        String forObject = restTemplate.getForObject(uri, String.class);// 返回一个Json对象，但是按照String来接收
        System.out.println(forObject);
        // 解析Json字符串
        JSONObject jsonObject = JSON.parseObject(forObject);
        Integer code = jsonObject.getInteger("code");//获取整形数值
        System.out.println(code);
        String msg = jsonObject.getString("message");//获取字符串
        System.out.println(msg);
        JSONObject data = jsonObject.getJSONObject("data");//获取下层Json对象
        System.out.println(data);


        return forObject;
    }

    /**
     * 测试传输Header参数
     * @return
     */
    @GetMapping("/post1")
    public Object post1(){
        String url = "http://localhost:8889/esungsc/index/testHeader";
        Map<String, String> uriVariables = new HashMap<>();
        uriVariables.put("str", "yuzudeng");

        // 置入Query参数
        String uri = HttpUtil.putQueryParam(url, uriVariables);

        // 置入Header参数
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization","7cNFyRzEKTt9JBtua1Op8QHAfJm9K7kuYLyTOeaEildkqMe+TtKv09+j9uyZNqPp");
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(headers);

        ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.POST, httpEntity, String.class);
        System.out.println(response.getStatusCode());
        System.out.println(response.getStatusCodeValue());
        System.out.println(response.getHeaders());
        System.out.println(response.getBody());

        return "success";
    }

    /**
     * 测试传输Body参数
     * @return
     */
    @GetMapping("/post2")
    public Object post2(){
        String url = "http://localhost:8889/esungsc/index/testBody";
        Map<String, String> uriVariables = new HashMap<>();
        uriVariables.put("str", "yuzudeng");

        // 置入Query参数
        String uri = HttpUtil.putQueryParam(url, uriVariables);

        // 置入Header参数
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
//        headers.add("Authorization","7cNFyRzEKTt9JBtua1Op8QHAfJm9K7kuYLyTOeaEildkqMe+TtKv09+j9uyZNqPp");
        // 置入Body参数, 这里要用Map而不是普通MultiValueMap
        // 场景一： Header参数和Body参数一起传时，body需要用Map
        // 场景二： 不传Header参数只传Body参数时，需要用MultiValueMap(只传Body时默认是form-data格式，需要接口支持)
        Map<String, Object> bodyParam = new HashMap<>();
        bodyParam.put("page", "page10");
        bodyParam.put("pageSize", 100);

        HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(bodyParam, headers);

        ResponseEntity<String> response = restTemplate.postForEntity(uri, httpEntity, String.class);
        System.out.println(response.getStatusCode());
        System.out.println(response.getStatusCodeValue());
        System.out.println(response.getHeaders());
        String responseBody = response.getBody();
        System.out.println(responseBody);
        // 解析Json字符串
        JSONObject jsonObject = JSON.parseObject(responseBody);
        String msg = jsonObject.getString("message");//获取字符串
        System.out.println("message:"+msg);

        return "success";
    }

    /**
     * 测试传输Header和Body参数
     * @return
     */
    @GetMapping("/post3")
    public Object post3(){
        String url = "http://localhost:8889/esungsc/index/testHeadAndBody";
        Map<String, String> uriVariables = new HashMap<>();
        uriVariables.put("str", "yuzudeng");

        // 置入Query参数
        String uri = HttpUtil.putQueryParam(url, uriVariables);

        // 置入Header参数
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Authorization","7cNFyRzEKTt9JBtua1Op8QHAfJm9K7kuYLyTOeaEildkqMe+TtKv09+j9uyZNqPp");
        // 置入Body参数, 这里要用Map而不是普通MultiValueMap
        // 场景一： Header参数和Body参数一起传时，body需要用Map
        // 场景二： 不传Header参数只传Body参数时，需要用MultiValueMap
        Map<String, Object> bodyParam = new HashMap<>();
        bodyParam.put("page", "page10");
        bodyParam.put("pageSize", 100);
        HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(bodyParam, headers);

        ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.POST, httpEntity, String.class);
        System.out.println(response.getStatusCode());
        System.out.println(response.getStatusCodeValue());
        System.out.println(response.getHeaders());
        String responseBody = response.getBody();
        System.out.println(responseBody);
        // 解析Json字符串
        JSONObject jsonObject = JSON.parseObject(responseBody);
        String msg = jsonObject.getString("message");//获取字符串
        System.out.println("message:"+msg);

        return "success";
    }


    /**
     * 测试传输Header和Body参数
     * @return
     */
    @GetMapping("/voucher")
    public Object testVoucherJson(){
        String url = "http://localhost:8889/esungsc/index/getVoucherList";
        Map<String, String> uriVariables = new HashMap<>();
        uriVariables.put("str", "yuzudeng");

        // 置入Query参数
        String uri = HttpUtil.putQueryParam(url, uriVariables);

        // 置入Header参数
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setAcceptLanguage(Locale.LanguageRange.parse("zh-CHS"));
        headers.add("X-ECC-Current-Tenant", "10000");
        headers.add("Authorization","Bearer 6b1204d4-639d-9bc5-6cd4-d0c2ec4f5d31");


        // 置入Body参数, 这里要用Map而不是普通MultiValueMap
        // 场景一： Header参数和Body参数一起传时，body需要用Map
        // 场景二： 不传Header参数只传Body参数时，需要用MultiValueMap
        Map<String, Object> bodyParam = new HashMap<>();
        bodyParam.put("page", "page10");
        bodyParam.put("pageSize", 100);
        HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(bodyParam, headers);

        ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.POST, httpEntity, String.class);
        System.out.println(response.getStatusCode());
        System.out.println(response.getStatusCodeValue());
        System.out.println(response.getHeaders());
        String responseBody = response.getBody();
//        System.out.println(responseBody);
        parseVoucher(responseBody);
        return responseBody;
    }

    private void parseVoucher(String jsonStr){
        // 解析Json字符串
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        String code = jsonObject.getString("code");//获取字符串
        if(code.equals("2")){
            log.info("请求凭证数据成功");
            JSONArray value = jsonObject.getJSONArray("value");
            int countVoucher  = value.size();
            System.out.println("countVoucher:"+countVoucher);
            int countEntry = 0;
            int countAssistance = 0;
            for (int i = 0; i < countVoucher  && i < 10; i++) {
                JSONObject element = value.getJSONObject(i);
                // 1、解析凭证头
                JSONObject figlaccountingdocument = element.getJSONObject("FIGLACCOUNTINGDOCUMENT");
                String abstracts = figlaccountingdocument.getString("ABSTRACTS");
                System.out.println(" accdoc abstracts:"+abstracts);
                // 2、解析凭证分录
                JSONArray figlaccdocentry = element.getJSONArray("FIGLACCDOCENTRY");
                countEntry += figlaccdocentry.size();
                for(int indexEntry = 0; indexEntry < figlaccdocentry.size(); indexEntry++){
                    JSONObject entry = figlaccdocentry.getJSONObject(indexEntry);
                    String entryID = entry.getString("ID");
                    System.out.println("entryID:"+entryID);
                }
                // 3、解析凭证辅助原始
                JSONArray figlaccdocassistance = element.getJSONArray("FIGLACCDOCASSISTANCE");
                countAssistance += figlaccdocassistance.size();
                for(int indexAss = 0; indexAss < figlaccdocassistance.size(); indexAss++){
                    JSONObject assistance = figlaccdocassistance.getJSONObject(indexAss);
                    String assistanceID = assistance.getString("ID");
                    System.out.println("assistanceID:"+assistanceID);
                }
            }

        }else{
            log.error("请求凭证数据失败");
        }

    }

    @GetMapping("/filePath")
    public Object filePath(){
        InputStream resourceAsStream = this.getClass().getResourceAsStream("/test/json/voucherData.json");
        try {
            assert resourceAsStream != null;
            try (Reader reader = new InputStreamReader(resourceAsStream, "utf-8")){
                int ch = 0;
                StringBuilder sb = new StringBuilder();
                while((ch= reader.read())!=-1){
                    sb.append((char) ch);
                }
                String jsonStr = sb.toString();
                JSONObject jsonObject = JSON.parseObject(jsonStr);
    //            System.out.println(jsonObject);
                return jsonObject;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


}
